<template>
  <div class="menu">
    <ToolBar :show-all="false" :show-multiple="false" :add-data="setAddDialogVisible" :delete-data="deleteById"
             :update-data="updateById" :show-add="true"></ToolBar>
    <el-form :inline="true" style="margin-left: 1rem">
      <el-col :span="5">
        <el-form-item label="字典类型">
          <el-select v-model="queryParam.codes" filterable clearable placeholder="请选择字典类型..." value-key="ccode"
                     size="small" multiple>
            <el-option v-for="item in types" :value="item.ccode" :label="item.cname">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="是否启用" >
          <el-select v-model="queryParam.valid" clearable size="small">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="字典类型名称" >
          <el-input v-model="queryParam.name" clearable size="small">
          </el-input>
        </el-form-item>
      </el-col>
      <el-form-item>
        <el-button type="primary" @click="handleCurrentChange(1)" size="small">筛选</el-button>
      </el-form-item>
    </el-form>
    <el-table
        border
        :data="tableData"
        row-key="ccode"
        :tree-props="{children:'children',hasChildren:'hasChildren'}">
      <el-table-column
          type="index"
          label="编号"
          width="60">
      </el-table-column>
      <el-table-column
          prop="cname"
          label="名称">
      </el-table-column>
      <el-table-column
          prop="norder"
          label="排序">
      </el-table-column>
      <el-table-column
          prop="ccode"
          label="编码">
      </el-table-column>
      <el-table-column
          label="值" prop="cvalue">
      </el-table-column>
      <el-table-column
          label="单位" prop="cunit">
      </el-table-column>
      <el-table-column label="生效时间" prop="dtEffectiveDate">
        <template slot-scope="scope" v-if="scope.row.dtEffectiveDate">
          {{ scope.row.dtEffectiveDate|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="失效时间" prop="dtExpiringDate">
        <template slot-scope="scope" v-if="scope.row.dtExpiringDate">
          {{ scope.row.dtExpiringDate|formatDate }}
        </template>
      </el-table-column>
      <el-table-column
          prop="delete"
          label="启用状态">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.nvalid" :disabled="scope.row.nsystem===1"
              :active-value="1"
              :inactive-value="0" @change="handleDelete(scope.row,false)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope" v-if="scope.row.nsystem!==1">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete( scope.row,true)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParam.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size=queryParam.limit
          layout="total, sizes, prev, pager, next, jumper"
          :total=queryParam.total>
      </el-pagination>
    </div>
    <el-dialog :title="'字典'+(operationType===0?'添加':'编辑')" top="5vh" :visible.sync="dialogVisible">
      <el-form :model="dict" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字典类别" :label-width="formLabelWidth" prop="type">
              <el-select v-model="dict.type" class="w100" filterable :disabled="operationType!==0">
                <el-option v-for="item in codes" :value="item.code" :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="dict.type === '2'">
            <el-form-item label="字典类型" :label-width="formLabelWidth" prop="cpcode" :rules="{
      required: dict.type === '2', message: '字典类型不能为空', trigger: 'blur'}">
              <el-select v-model="dict.cpcode" class="w100" filterable :disabled="operationType!==0">
                <el-option v-for="item in codeTypes" :value="item.ccode" :label="item.cname">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="系统配置" :label-width="formLabelWidth" prop="nsystem">
              <el-select v-model="dict.nsystem" placeholder="请选择..." size="small" filterable clearable class="w100">
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典名称" :label-width="formLabelWidth" prop="cname">
              <el-input v-model="dict.cname" autocomplete="off" class="w100"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典编码" :label-width="formLabelWidth" prop="ccode">
              <el-input v-model="dict.ccode" autocomplete="off" class="w100" :disabled="operationType!==0"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dict.type === '2'">
            <el-form-item label="参数值" :label-width="formLabelWidth" prop="nvalue">
              <el-input-number v-model="dict.cvalue" :precision="2" :step="0.1" :min="0" class="w100"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dict.type === '2'">
            <el-form-item label="参数单位" :label-width="formLabelWidth" prop="cunit">
              <el-input v-model="dict.cunit" autocomplete="off" class="w100"
                        :disabled="false"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="norder" label="顺序" :label-width="formLabelWidth">
              <el-input v-model="dict.norder" autocomplete="off" class="w100" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" :label-width="formLabelWidth" prop="nvalid">
              <el-radio-group v-model="dict.nvalid">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生效时间" :label-width="formLabelWidth" prop="dteffectiveDate">
              <el-date-picker type="datetime" v-model="dict.dteffectiveDate" class="w100"
                              :disabled="operationType!==0&& copy.dteffectiveDate !=null"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" :label-width="formLabelWidth" prop="dtexpiringDate">
              <el-date-picker type="datetime" v-model="dict.dtexpiringDate" class="w100"
                              :disabled="operationType!==0&& copy.dtexpiringDate !=null"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDict" v-if="operationType===0">确 定 添 加</el-button>
        <el-button type="primary" @click="addDict" v-else>确 定 修 改</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";

export default {
  name: "Menu",
  components: {ToolBar},
  data() {
    // 检查生效日期
    var checkStart = (rule, value, callback) => {
      if (!this.dict.dtexpiringDate) {
        callback();
      } else {
        if (!value) {
          callback(new Error('生效日期不能为空！'));
        } else {
          var start = new Date(value);
          var end = new Date(this.dict.dtexpiringDate);
          if (start > end) {
            callback(new Error('生效日期不能大于失效日期！'));
          } else {
            callback();
          }
        }
      }
    };
    // 检查失效日期
    var checkEnd = (rule, value, callback) => {
      if (!this.dict.dteffectiveDate) {
        callback();
      } else {
        if (!value) {
          callback();
        } else {
          var start = new Date(this.dict.dteffectiveDate);
          var end = new Date(value);
          if (end < start) {
            callback(new Error('失效日期不能小于生效日期！'));
          } else {
            callback();
          }
        }
      }
    };
    // 检查编码是否重复
    var checkCode = (rule, value, callback) => {
      if (!this.dict.type) {
        callback(new Error('请先选择字典类别！'));
        return;
      }
      // 选择字典码值时
      if (this.dict.type === '2') {
        if (!this.dict.cpcode) {
          callback(new Error('请先选择字典类型！'));
          return;
        }
      }
      if (!value) {
        callback();
        return;
      }
      if (this.operationType !== 0) {
        callback();
        return;
      }
      this.validateCode(rule, value, callback);
    };
    return {
      queryParam: {
        codes: [],
        name: null,
        limit: 10,
        page: 1,
        total: 0
      },
      codes: fdCommon.getCodesByPid('10001'),
      codeTypes: [],
      types: [],
      tableData: [],
      treeData: [],
      defaultProps: {
        children: 'menuList',
        label: 'menuName'
      },
      dict: {
        type: null,
        cpcode: null,
        ccode: null,
        cname: null,
        cvalue: null,
        cunit: null,
        norder: null,
        nvalid: null,
        nsystem: null,
        dteffectiveDate: null,
        dtexpiringDate: null
      },
      copy: {},
      operationType: 0,
      dialogVisible: false,
      formLabelWidth: '100px',
      iconList: [],
      rules: {
        type: [
          {required: true, message: '请选择字典类别...', trigger: 'change'},
        ],
        cname: [
          {required: true, message: '请输入字典名称...', trigger: 'blur'}
        ],
        ccode: [
          {required: true, message: '请输入字典编码...', trigger: 'blur'},
          {validator: checkCode, trigger: 'blur'}
        ],
        norder: [
          {required: true, message: '请设置显示顺序...', trigger: 'blur'}
        ],
        nvalid: [
          {required: true, message: '请选择是否启用...', trigger: 'blur'}
        ],
        nsystem: [{required: true, message: '请选择是否系统配置...', trigger: 'blur'}],
        dteffectiveDate: [{validator: checkStart, trigger: 'blur'}],
        dtexpiringDate: [{validator: checkEnd, trigger: 'blur'}]
      }
    }
  },
  watch: {
    dialogVisible: {
      handler(newVal, oldVal) {
        if (oldVal) {
          this.menu = {}
        }
      }
    }
  },
  created() {
    this.getDataList()
    this.loadCodeTypes();
  },
  methods: {
    // 加载所有codeType
    loadCodeTypes() {
      this.codeTypes = [];
      this.types = [];
      axios.get(window.fdConfig.url.tcodeType.selectAll).then(res => {
        if (res.data.success && res.data.data && res.data.data.length > 0) {
          this.types = res.data.data;
          this.codeTypes = this.types.filter((item=>item.nvalid === 1));
        }
      }).catch(error => {
        console.log(error)
      })
    },
    validateCode(rule, value, callback) {
      axios.get(window.fdConfig.url.tcode.validate + '?type=' + this.dict.type + '&code=' + this.dict.ccode + '&pcode=' + this.dict.cpcode).then(res => {
        if (res.data.success && res.data.data) {
          callback(new Error('编码重复！'));
        } else {
          callback();
        }
      }).catch(error => {
        console.log(error)
      })
    },
    handleConfig(row,type,configMessage) {
      this.$tools.showMessageBox(configMessage , "操作确认", "warning").then(confirm => {
        this.$tools.openLoading();
        let _url = fdConfig.url.tcodeType.delete.replace('{code}',row.ccode);
        if(type === '2'){
          _url = fdConfig.url.tcode.delete.replace('{id}',row.id);
        }
        axios.delete(_url).then(res => {
          this.$tools.closeLoading();
          if (res) {
            this.$tools.showMessage("操作成功", "success")
            this.getDataList()
            this.loadCodeTypes();
          } else {
            this.$tools.showMessage("操作失败", "error")
          }
        }).catch(error =>{
          this.$tools.closeLoading();
        })
      }).catch(cancel => {

      })
    },
    handleEdit(index, row) {
      this.operationType = 1
      this.dict = this.$tools.deepClone(row)
      if (this.dict.cpcode) {
        this.dict.type = '2';
      } else {
        this.dict.type = '1';
      }
      this.copy = this.$tools.deepClone(row)
      this.dialogVisible = true
    },
    handleDelete(row,isDel) {
      this.dict = this.$tools.deepClone(row)
      if (this.dict.cpcode) {
        this.dict.type = '2';
      } else {
        this.dict.type = '1';
      }
      if(isDel){
        this.handleConfig(this.dict,this.dict.type,this.dict.type === '1'?'删除字典类型将导致此类型下的字典码值一起被删除，确认删除吗？':'确认要删除这个字典码值吗？');
        return;
      }
      this.edtiDict();
    },
    getDataList() {
      axios.post(fdConfig.url.tcodeType.page, this.queryParam).then(res => {
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.queryParam.total = res.data.data.total
          this.queryParam.page = res.data.data.pages
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryParam.limit = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParam.page = val
      this.getDataList()
    },
    setAddDialogVisible() {
      this.operationType = 0;
      this.dialogVisible = true
    },
    edtiDict(){
      this.dict.cCreateUser = this.$store.state.userInfo.id
      axios.post(fdConfig.url.tcode.saveOrUpdate, this.dict).then(res => {
        if (res.data.success) {
          this.$tools.showMessage('操作成功', "success")
          this.getDataList()
          this.dialogVisible = false
          this.operationType = 0
          this.dict = {}
          this.loadCodeTypes();
        } else {
          this.$tools.showMessage('操作失败', "error")
        }
      })
    },
    addDict() {
      if (this.$refs.ruleForm.validate((valid => {
        if (valid) {
            this.edtiDict();
        } else {
          this.$tools.showMessage("请完善表单信息...", 'warning')

        }
      }))) ;

    }
  }
}
</script>

<style scoped>

</style>
